import string,os,glob,zipfile,fnmatch
from path import path
_dry_run = False

def init_env():
    global _env_ns

    _env_ns = {}

init_env()

def e(s):
    tmp = string.Template(s) 
    return tmp.substitute(_env_ns)

def gl(s):
    return [path(p) for p in glob.glob(e(s))]
    
def decl(**vars):
    _env_ns.update(vars)

def unzip_bin(src,tgt):
    tgt = path(e(tgt))
    if not tgt.isdir():
        #log.debug( "Creating %s" % tgt )
        tgt.makedirs()
    
    zips = gl(src)
    if not zips:
        print "No zips match", e(src)
    for s in zips:
        if _dry_run:
            print "DryRun: unzip %s => %s" %(s,tgt)
            return
        os.system('unzip -o %s -d %s' % (s,tgt))

unzip = unzip_bin

def unzip_files_bin(zipnames, tgt, pats = ['*']):
    tgt = path(e(tgt))
    for s in gl(zipnames):
        zf = zipfile.ZipFile(s)
        namelist = zf.namelist()
        for name in namelist:
            #name = path(name)
            found = False
            for pat in pats:
                if fnmatch.fnmatch(os.path.basename(name), pat):
                    found = True
                    break
            if found:
                print "Extracting file",os.path.basename(name)
                
                os.system('unzip -oj %s %s -d %s' % (s, name, tgt))

unzip_files = unzip_files_bin

def cd(dir):
    os.chdir(e(dir))

def rm(**files):
    for g in files:
        for f in gl(g):
            os.remove(f)

def oscmd(cmd):
    print ">",cmd
    os.system(e(cmd))
        
    
class RequirementNotFulfilled(Exception):
    pass

def require(req):
    req = e(req)
    if not os.path.exists(req) and req not in _env_ns:
        print "Not fullfilled",req
        raise RequirementNotFulfilled(req)

